#!/usr/bin/env python3
"""
最简单可运行的 MCP 服务器
"""
import asyncio
import sys
from mcp.server import Server
from mcp.server.stdio import stdio_server

# 设置标准输出编码为 UTF-8，避免中文和表情符号问题
if sys.stdout.encoding != 'utf-8':
    sys.stdout.reconfigure(encoding='utf-8')
if sys.stderr.encoding != 'utf-8':
    sys.stderr.reconfigure(encoding='utf-8')

# 创建服务器
server = Server("demo-server")

@server.list_tools()
async def handle_list_tools():
    """返回可用工具"""
    return [
        {
            "name": "echo",
            "description": "回显输入的文字",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "message": {"type": "string", "description": "要回显的消息"}
                },
                "required": ["message"]
            }
        },
        {
            "name": "add_numbers",
            "description": "两个数字相加",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "a": {"type": "number", "description": "第一个数字"},
                    "b": {"type": "number", "description": "第二个数字"}
                },
                "required": ["a", "b"]
            }
        }
    ]

@server.call_tool()
async def handle_call_tool(name: str, arguments: dict):
    """处理工具调用"""
    if name == "echo":
        return [{"type": "text", "text": f"回显: {arguments['message']}"}]
    elif name == "add_numbers":
        result = arguments['a'] + arguments['b']
        return [{"type": "text", "text": f"结果: {result}"}]
    else:
        return [{"type": "text", "text": f"未知工具: {name}"}]

async def main():
    """主函数"""
    print("MCP 服务器启动...")
    try:
        async with stdio_server() as streams:
            await server.run(streams[0], streams[1], {})
    except Exception as e:
        print(f"错误: {e}")

if __name__ == "__main__":
    asyncio.run(main())